﻿using System.Linq;
using System.Web.Mvc;
using Yyyg.Models;
using Yyyg.WebUI.Models;

namespace Yyyg.WebUI.Controllers
{
    public class SpAddrController : Controller
    {
        // GET: Addr
        public ActionResult AddrForm()
        {
            AddrVM vm = new AddrVM();
            return View(vm);
        }

        [HttpPost]
        public JsonResult Add(AddrVM addr)
        {
            PostResult result = new PostResult();
            result.Isucc = false;
            int uid = HttpContext.GetUserID();
            if (ModelState.IsValid && uid > 0)
            {
                using (LuckyEntities db = new LuckyEntities())
                {
                    ReceInfo rece;
                    if (addr.Id > 0) rece = db.ReceInfo.FirstOrDefault(s => s.Id == addr.Id);
                    else rece = new ReceInfo();
                    rece.Proe = db.Region.First(s => s.Id == addr.ProvinceCode).Name;
                    rece.City = db.Region.First(s => s.Id == addr.CityCode).Name;
                    rece.Area = db.Region.First(s => s.Id == addr.CountyCode).Name;
                    rece.Consianee = addr.ConsigneeName;
                    rece.Uid = uid;
                    rece.Det = addr.Detarea;
                    rece.Mobile = addr.ConsigneeMobel;
                    rece.IsDefault = addr.SetDef == "on";
                    //如果是添加请求
                    if (addr.Id < 0)
                    {
                        if (db.ReceInfo.Count(c => c.Uid == uid) <= 20) db.ReceInfo.Add(rece);
                        else result.ErrorMsg = "超出地址添加限制!";
                    }
                    result.Isucc = db.SaveChanges() > 0;
                }
            }
            return Json(result);
        }

        [HttpPost]
        public JsonResult Remove(int id)
        {
            PostResult result = new PostResult();
            using (LuckyEntities db = new LuckyEntities())
            {
                var rece = db.ReceInfo.FirstOrDefault(s => s.Id == id);
                if (rece != null)
                {
                    db.ReceInfo.Remove(rece);
                    result.Isucc = db.SaveChanges() > 0;
                }
                else
                {
                    result.Errors.Add("无效的地址编号");
                }
            }
            return Json(result);
        }

        [HttpPost]
        public JsonResult SetDefault(int id)
        {
            PostResult result = new PostResult();
            using (LuckyEntities db = new LuckyEntities())
            {
                var rec = db.ReceInfo.FirstOrDefault(s => s.Id == id);
                if (rec != null)
                {
                    rec.IsDefault = true;
                    result.Isucc = db.SaveChanges() > 0;
                }
            }
            return Json(result);
        }
    }
}